#include "get_date.h"
#include <windows.h>
#include <QDebug>
#include <QTimer>
#include <QSerialPort>
#include <QDebug>
static int flag_get =0;
QTimer timer;
QSerialPort port;
QSerialPort serialport;
static int serialport_date = 0;
static int bmp = 200;
static int ibi = 0;
Get_date::Get_date()
{
    qDebug()<<"Qthread is run";



    serialport.setPortName("COM6");
    serialport.open(QIODevice::ReadWrite);
    serialport.setBaudRate(115200);
    serialport.setDataBits(QSerialPort::Data8);
    serialport.setParity(QSerialPort::NoParity);
    serialport.setStopBits(QSerialPort::OneStop);
    serialport.setFlowControl(QSerialPort::NoFlowControl);
    connect(&serialport,SIGNAL(readyRead()),this,SLOT(read_serialport()));

}

void Get_date::run()
{
    connect(&timer,SIGNAL(timeout()),this,SLOT(timerout()));
    timer.start(100);
}

Get_date::~Get_date()
{
    timer.stop();
    qDebug()<<"Qthread is exit";
}

void Get_date::change_get_flag(int temp)
{
    flag_get = temp;
}

void Get_date::timerout()
{


    switch (flag_get)
    {
    case 0:                 //串口

        break;
    case 1:                 //网口
        emit send_date(1,rand()%300,0,0,0);
        break;
    case 2:                 //蓝牙
        emit send_date(2,rand()%300,0,0,0);
        break;
    default:
        break;
    }
}
static bool q_flag = true;
void Get_date::read_serialport()
{
    QByteArray temp;
    temp = serialport.readAll();
//    qDebug()<<bmp<<temp;
    serialport_date = temp.mid(1,3).toInt();
    if(temp.length()>6)
    {
        int temp1=0;
        if((temp1 = temp.indexOf("B"))>0)
        {
            QByteArray temp3 = temp.mid(temp1+1);
            int temp2 = temp3.indexOf("\r");
            bmp = temp3.mid(0,temp2).toInt();
        }

        if((temp1 = temp.indexOf("Q"))>0)
        {
            QByteArray temp3 = temp.mid(temp1+1);
            int temp2 = temp3.indexOf("\r");
            ibi = temp3.mid(0,temp2).toInt();
            q_flag = true;
        }
        else
        {
           q_flag = false;
        }


    }
    if(flag_get == 0)
    {
        if(q_flag)
        {
            emit send_date(0,serialport_date,bmp,ibi,1);

        }
        else
        {
            emit send_date(0,serialport_date,bmp,ibi,0);
        }
    }


}
